package com.sjt.blog.service;

import com.sjt.blog.NotFoundException;
import com.sjt.blog.dao.BlogRepository;
import com.sjt.blog.po.Blog;
import com.sjt.blog.po.Type;
import com.sjt.blog.util.MarkdownUtils;
import com.sjt.blog.util.MyBeanUtils;
import com.sjt.blog.vo.BlogQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.*;

@Service
public class BlogServiceImpl implements BlogService {

    @Autowired
    private BlogRepository blogRepository;

    @Transactional
    @Override
    public Blog getBlog(Long id) {
        Optional<Blog> b = blogRepository.findById(id);
        if (!b.isPresent()) {
            throw new NotFoundException("该博客不存在！");
        }
        return b.get();
    }

    // 获取博客，并将markdown文本转换为html文本
    @Transactional
    @Override
    public Blog getAndConvert(Long id) {
        blogRepository.updateViews(id);
        Optional<Blog> o = blogRepository.findById(id);
        if (!o.isPresent()) {
            throw new NotFoundException("该博客不存在！");
        }
        Blog blog = new Blog();
        BeanUtils.copyProperties(o.get(), blog);
        String content = blog.getContent();
        blog.setContent(MarkdownUtils.markdownToHtmlExtensions(content));
        return blog;
    }

    @Transactional
    @Override
    public Page<Blog> listBlog(Pageable pageable, BlogQuery blogQuery) {
        // 按照一定规则查询 可实现模糊查询
        return blogRepository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (blogQuery.getTitle() != null && !blogQuery.getTitle().equals("")) {
                    predicates.add(cb.like(root.<String>get("title"), "%" + blogQuery.getTitle() + "%"));
                }
                if (blogQuery.getTypeId() != null) {
                    predicates.add(cb.equal(root.<Type>get("type"), blogQuery.getTypeId()));
                }
                if (blogQuery.isRecommend()) {
                    predicates.add(cb.equal(root.<Boolean>get("recommend"), blogQuery.isRecommend()));
                }
                cq.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        }, pageable);
    }

    @Transactional
    @Override
    public Page<Blog> listBlog(Pageable pageable) {
        return blogRepository.findAll(pageable);
    }


    @Override
    public Page<Blog> listBlog(Pageable pageable, Long tagId) {
        // 按照一定规则查询 实现关联查询 多表查询
        return blogRepository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                // tags 是Blog类中的一个属性，是tag表
                Join join = root.join("tags");
                return cb.equal(join.get("id"), tagId);
            }
        }, pageable);
    }

    // 模糊查询
    @Transactional
    @Override
    public Page<Blog> listBlog(String query, Pageable pageable) {
        return blogRepository.findByQurey("%" + query + "%", pageable);
    }

    @Transactional
    @Override
    public List<Blog> listRecommendBlogTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC, "updateTime");
        Pageable pageable = new PageRequest(0, size, sort);
        return blogRepository.findTop(pageable);
    }

    // 归档
    @Override
    public Map<String, List<Blog>> archiveBlog() {
        // 获取年份
        List<String> years = blogRepository.findGroupYear();
        Map<String, List<Blog>> map = new LinkedHashMap<>();

        // 查询年份中的博客，并保存到map
        for (String year : years){
            map.put(year, blogRepository.findByYear(year));
        }

        return map;
    }

    @Override
    public Long countBlog() {
        return blogRepository.count();
    }

    @Transactional
    @Override
    public Blog saveBlog(Blog blog) {
        blog.setCreateTime(new Date());
        blog.setUpdateTime(new Date());
        blog.setViews(0);
        return blogRepository.save(blog);
    }

    @Transactional
    @Override
    public Blog updateBlog(Long id, Blog blog) {
        Optional<Blog> b = blogRepository.findById(id);
        if (!b.isPresent()) {
            throw new NotFoundException("该博客不存在！");
        }
        BeanUtils.copyProperties(blog, b.get(), MyBeanUtils.getNullPropertyNames(blog));
        b.get().setUpdateTime(new Date());
        return blogRepository.save(b.get());
    }

    @Transactional
    @Override
    public void deleteBlog(Long id) {
        blogRepository.deleteById(id);
    }
}
